<script setup lang="ts">
import { DiyRouter, HeaderNav } from './components'
import pageEmitter from '@/common/mitt/page'
import LoginDia from '@/components/LoginDia.vue'
import type { RouteRecordName } from 'vue-router'
type listItem = {
  names: RouteRecordName[]
  path: string
  scroll: number
}
const route = useRoute()
const pageRef = ref<HTMLElement | undefined>(undefined)
const { y } = useScroll(pageRef)
provide('scroll', y)
provide('pageRef', pageRef)
let historyList: listItem[] = []
pageEmitter.on('scroll', (data: any) => {
  pageRef.value?.scrollTo(data)
})
pageEmitter.on('addLog', () => {
  const names: string[] = []
  toRaw(route).matched.forEach(el => {
    if (el && el?.name) {
      names.push(String(el.name))
    }
  })
  names.pop()
  const index = historyList.findIndex(el => el.path === route.path)
  if (index >= 0) {
    historyList[index].scroll = toRaw(y.value)
  } else {
    historyList.push({
      path: route.path,
      names,
      scroll: toRaw(y.value)
    })
  }
})
const rollback = () => {
  const index = historyList.findIndex(el => el.path === route.path)
  if (index >= 0) {
    const info = historyList[index]
    const dom = pageRef.value
    if (dom) {
      dom.scrollTop = info.scroll
    }
    historyList.splice(index, 1)
  }
}
pageEmitter.on('rollback', () => rollback())

watch(route, newVal => {
  const index = historyList.findIndex(el => el.path === newVal.path)
  if (index < 0) {
    const dom = pageRef.value
    if (dom) {
      dom.scrollTop = 0
    }
    if (!newVal.meta?.isPage) {
      historyList = []
    }
  }
})
</script>

<template>
  <div class="layout-page">
    <header-nav v-if="route.name !== 'Detail'" :scroll="y" />
    <div class="layout-page-main" ref="pageRef">
      <DiyRouter superiorName="Root" />
      <n-back-top :listen-to="pageRef" />
    </div>
    <login-dia />
  </div>
</template>

<style lang="scss" scoped>
.layout-page {
  flex: 1;
  display: flex;
  flex-direction: column;
  &-main {
    flex: 1 0 0;
    overflow-y: scroll;
    background: var(--yang-bg-color);
    box-sizing: border-box;
    position: relative;
  }
}
@media (max-width: 800px) {
  .layout-page {
    width: 320px;
  }
}
</style>
